<template>
  <div class="device-container">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="hover">
      <el-row :gutter="20">
        <el-col :span="20">
          <el-form :inline="true" :model="formSearch" class="search-form">
            <el-form-item>
              <el-select v-model="formSearch.online_status" placeholder="设备状态" clearable size="small">
                <el-option label="在线" :value="1">
                  <i class="el-icon-success" style="color: #67C23A"></i> 在线
                </el-option>
                <el-option label="离线" :value="0">
                  <i class="el-icon-error" style="color: #F56C6C"></i> 离线
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select v-model="formSearch.bind_status" placeholder="绑定状态" clearable size="small">
                <el-option label="未绑定" :value="0">
                  <i class="el-icon-lock" style="color: #E6A23C"></i> 未绑定
                </el-option>
                <el-option label="已绑定" :value="1">
                  <i class="el-icon-unlock" style="color: #409EFF"></i> 已绑定
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-input
                v-model="formSearch.name"
                placeholder="设备名称/编号"
                clearable
                size="small"
                prefix-icon="el-icon-search"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="small" @click="toSearch">搜索</el-button>
              <el-button icon="el-icon-refresh" size="small" @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="4" style="text-align: right;">
          <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAdd">录入</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table :data="empData" style="width: 100%" v-loading="loading">
        <el-table-column type="index" :index="indexMethod" label="序号" width="60" align="center">
        </el-table-column>
        <el-table-column prop="serial_number" label="编号" width="100" align="center">
        </el-table-column>
        <el-table-column prop="name" label="名称" width="700">
        </el-table-column>
        <el-table-column prop="online_status" label="在线状态" align="center">
          <template v-slot="scope">
            <el-tag :type="scope.row.online_status === 1 ? 'success' : 'info'" size="small">
              {{ scope.row.online_status === 1 ? '在线' : '离线' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="bind_status" label="绑定状态" align="center">
          <template v-slot="scope">
            <el-tag :type="scope.row.bind_status === 1 ? 'primary' : 'warning'" size="small">
              {{ scope.row.bind_status === 1 ? '已绑定' : '未绑定' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template v-slot="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button type="text" size="small" @click="handleDelete(scope.row)" class="text-danger">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="params.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="params.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加设备对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" @close="resetForm">
      <el-form :model="deviceForm" :rules="rules" ref="deviceForm" label-width="100px" size="small">
        <el-form-item label="设备编号" prop="serial_number">
          <el-input v-model="deviceForm.serial_number" placeholder="请输入设备编号"></el-input>
        </el-form-item>
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="deviceForm.name" placeholder="请输入设备名称"></el-input>
        </el-form-item>
        <el-form-item label="在线状态" prop="online_status">
          <el-select v-model="deviceForm.online_status" placeholder="请选择在线状态" style="width: 100%">
            <el-option label="在线" :value="1"></el-option>
            <el-option label="离线" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="绑定状态" prop="bind_status">
          <el-select v-model="deviceForm.bind_status" placeholder="请选择绑定状态" style="width: 100%">
            <el-option label="未绑定" :value="0"></el-option>
            <el-option label="已绑定" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="deviceForm.remark" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 查看设备详情对话框 -->
    <el-dialog title="设备详情" :visible.sync="viewDialogVisible" width="500px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="设备编号">{{ viewForm.serial_number }}</el-descriptions-item>
        <el-descriptions-item label="设备名称">{{ viewForm.name }}</el-descriptions-item>
        <el-descriptions-item label="在线状态">
          <el-tag :type="viewForm.online_status === 1 ? 'success' : 'info'" size="small">
            {{ viewForm.online_status === 1 ? '在线' : '离线' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="绑定状态">
          <el-tag :type="viewForm.bind_status === 1 ? 'primary' : 'warning'" size="small">
            {{ viewForm.bind_status === 1 ? '已绑定' : '未绑定' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注">{{ viewForm.remark || '暂无备注' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ viewForm.create_time }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ viewForm.update_time }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="viewDialogVisible = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { get, post, put, del } from '@/utils/request'

export default {
  data() {
    return {
      formSearch: {},
      empData: [],
      loading: false,
      total: 0,
      params: {
        page: 1,
        pageSize: 10
      },
      dialogVisible: false,
      viewDialogVisible: false,
      dialogTitle: '添加设备',
      submitLoading: false,
      deviceForm: {
        serial_number: '',
        name: '',
        online_status: 1,
        bind_status: 0,
        remark: ''
      },
      viewForm: {},
      rules: {
        serial_number: [
          { required: true, message: '请输入设备编号', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入设备名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        online_status: [
          { required: true, message: '请选择在线状态', trigger: 'change' }
        ],
        bind_status: [
          { required: true, message: '请选择绑定状态', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    // 重置搜索
    resetSearch() {
      this.formSearch = {}
      this.toSearch()
    },
    // 搜索
    toSearch() {
      this.params.page = 1
      this.getEmpData()
    },
    // 处理每页显示数量变化
    handleSizeChange(val) {
      this.params.pageSize = val
      this.getEmpData()
    },
    // 处理页码变化
    handleCurrentChange(val) {
      this.params.page = val
      this.getEmpData()
    },
    // 计算序号
    indexMethod(index) {
      return (this.params.page - 1) * this.params.pageSize + index + 1
    },
    // 获取设备数据
    async getEmpData() {
      this.loading = true
      try {
        const temp = {
          ...this.params,
          ...this.formSearch
        }
        const res = await get('/device/pageQuery', temp)
        this.empData = res.data.list
        this.total = res.data.total
      } catch (error) {
        console.error('获取设备数据失败:', error)
        this.$message.error('获取设备数据失败')
      } finally {
        this.loading = false
      }
    },
    // 打开添加设备对话框
    handleAdd() {
      this.dialogTitle = '添加设备'
      this.dialogVisible = true
      this.deviceForm = {
        serial_number: '',
        name: '',
        online_status: 1,
        bind_status: 0,
        remark: ''
      }
    },
    // 打开编辑设备对话框
    handleEdit(row) {
      this.dialogTitle = '编辑设备'
      this.dialogVisible = true
      this.deviceForm = { ...row }
    },
    // 查看设备详情
    handleView(row) {
      this.viewForm = { ...row }
      this.viewDialogVisible = true
    },
    // 重置表单
    resetForm() {
      this.$refs.deviceForm?.resetFields()
      this.deviceForm = {
        serial_number: '',
        name: '',
        online_status: 1,
        bind_status: 0,
        remark: ''
      }
    },
    // 提交表单
    submitForm() {
      this.$refs.deviceForm.validate(async (valid) => {
        if (valid) {
          this.submitLoading = true
          try {
            if (this.deviceForm.id) {
              // 编辑设备
              await put('/device', this.deviceForm)
              this.$message.success('编辑成功')
            } else {
              // 添加设备
              await post('/device', this.deviceForm)
              this.$message.success('添加成功')
            }
            this.dialogVisible = false
            this.getEmpData()
          } catch (error) {
            console.error('操作失败:', error)
            this.$message.error('操作失败')
          } finally {
            this.submitLoading = false
          }
        }
      })
    },
    // 删除设备
    handleDelete(row) {
      this.$confirm('确认删除该设备吗？删除后不可恢复！', '警告', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'el-button--danger'
      }).then(async () => {
        try {
          await del(`/device/${row.id}`)
          this.$message.success('删除成功')
          // 如果当前页只有一条数据，删除后跳转到上一页
          if (this.empData.length === 1 && this.params.page > 1) {
            this.params.page--
          }
          this.getEmpData()
        } catch (error) {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }).catch(() => {})
    }
  },
  created() {
    this.getEmpData()
  }
}
</script>

<style lang="scss" scoped>
.device-container {
  padding: 15px;
  
  .search-card {
    margin-bottom: 15px;
    
    .search-form {
      .el-form-item {
        margin-bottom: 10px;
        margin-right: 15px;
        
        &:last-child {
          margin-right: 0;
        }
      }
      
      .el-input {
        width: 220px;
      }
      
      .el-select {
        width: 140px;
      }
    }
  }
  
  .table-card {
    .el-table {
      margin-bottom: 15px;
    }
  }
  
  .pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 15px;
  }
  
  .text-danger {
    color: #F56C6C;
  }
}

// 状态标签样式
.el-tag--success {
  background-color: #f0f9eb;
}

.el-tag--info {
  background-color: #f4f4f5;
}

.el-tag--primary {
  background-color: #ecf5ff;
}

.el-tag--warning {
  background-color: #fdf6ec;
}

.dialog-footer {
  text-align: right;
}

.el-descriptions {
  margin: 15px 0;
}

.el-descriptions-item {
  margin-bottom: 10px;
}

.el-textarea {
  width: 100%;
}
</style>